<?php
namespace app\site\controller;

use app\common\model\ShopDeliveryModel;
use think\Request;

class ShopDeliveryController extends BaseController
{

    private $model;

    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->model = new ShopDeliveryModel();
    }

    /**
     * 模板列表
     * @return mixed
     *
     */
    public function index()
    {
        $list = $this->model->where('site_id', $this->getSiteId())->paginate(12);
        $this->assign('list', $list);
        return $this->fetch();
    }

    /**
     * 设置默认
     * @param $deliveryId
     */
    private function setDefault($deliveryId)
    {
        $this->model->where('site_id', $this->getSiteId())->setField('is_default', 0);
        $this->model->where('delivery_id', $deliveryId)->setField('is_default', 1);
        return true;
    }

    /**
     * 模板添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data   = $this->request->param();
            $data['site_id'] = $this->getSiteId();
            $result = $this->validate($data, 'ShopDeliveryValidate');
            if (true !== $result) {
                $this->error($result);
            }
            $this->model->addData($data);
            if ($data['is_default'] == 1) {
                $this->setDefault($this->model->delivery_id);
            }
            $this->success('添加成功！', url('index'));
        } else {
            return $this->fetch();
        }
    }

    /**
     * 模板修改
     * @return mixed
     */
    public function edit()
    {
        if ($this->request->isPost()) {
            $data   = $this->request->param();
            $result = $this->validate($data, 'ShopDeliveryValidate');
            if (true !== $result) {
                $this->error($result);
            }
            $this->model->editData($data);
            if ($data['is_default'] == 1) {
                $this->setDefault($this->model->delivery_id);
            }
            $this->success('添加成功！', url('index'));
        } else {
            $deliveryId = $this->request->param('delivery_id/d');
            $info       = $this->model->get($deliveryId);
            $this->assign('info', $info);
            return $this->fetch();
        }
    }

    /**
     * 模板修改
     */
    public function del()
    {
        $deliveryId = $this->request->param('delivery_id/d');
        $this->model->destroy($deliveryId);
        $this->success('删除成功！');
    }
}